package com.alogic.commonmark.html;

import com.alogic.load.Loader;
import com.alogic.textfilter.TextFilter;
import com.alogic.textfilter.TextFilterFactory;
import com.anysoft.util.Settings;
import org.commonmark.node.HtmlBlock;
import org.commonmark.node.HtmlInline;
import org.commonmark.node.Node;
import org.commonmark.renderer.NodeRenderer;
import org.commonmark.renderer.html.HtmlNodeRendererContext;
import org.commonmark.renderer.html.HtmlWriter;

import java.util.*;

/**
 * InlineHtmlNodeRenderer
 *
 * @since  1.6.13.16 [20200910 duanyy] <br>
 */
public class InlineHtmlNodeRenderer implements NodeRenderer {
    private final HtmlWriter html;
    private final HtmlNodeRendererContext context;
    private TextFilter filter = null;

    public InlineHtmlNodeRenderer(HtmlNodeRendererContext context,String filterId) {
        this.html = context.getWriter();
        this.context = context;

        Loader<TextFilter> loader = TextFilterFactory.getDefault();
        if (loader != null){
            filter = loader.load(filterId,true);
        }
    }

    @Override
    public Set<Class<? extends Node>> getNodeTypes() {
        return new HashSet(Arrays.asList(HtmlInline.class, HtmlBlock.class));
    }

    @Override
    public void render(Node node) {
        if (node instanceof HtmlInline){
            renderHtmlInline((HtmlInline)node);
        }else{
            if (node instanceof HtmlBlock){
                renderHtmlBlock((HtmlBlock)node);
            }
        }
    }

    protected void renderHtmlInline(HtmlInline node) {
        if (this.context.shouldEscapeHtml()) {
            this.html.text(node.getLiteral());
        } else {
            if (filter != null){
                this.html.raw(filter.doFilter(node.getLiteral(), Settings.get()));
            }else{
                this.html.raw(node.getLiteral());
            }
        }
    }

    protected void renderHtmlBlock(HtmlBlock node) {
        this.html.line();
        if (this.context.shouldEscapeHtml()) {
            this.html.tag("p", this.getAttrs(node, "p"));
            this.html.text(node.getLiteral());
            this.html.tag("/p");
        } else {
            if (filter != null){
                this.html.raw(filter.doFilter(node.getLiteral(), Settings.get()));
            }else{
                this.html.raw(node.getLiteral());
            }
        }
        this.html.line();
    }

    private Map<String, String> getAttrs(Node node, String tagName) {
        Map<String, String> empty = Collections.emptyMap();
        return this.getAttrs(node, tagName, empty);
    }

    private Map<String, String> getAttrs(Node node, String tagName, Map<String, String> defaultAttributes) {
        return this.context.extendAttributes(node, tagName, defaultAttributes);
    }
}
